package day27;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

//向服务端无限写入数据，还要负责接收服务给我返回的数据
public class Client3 {
    public static void main(String[] args) throws IOException {
        Socket client=new Socket("192.168.9.200",9999);
        //负责读取服务端写入的数据（负责读取和负责写入是相互独立的，而且美国人都不同）
        //所以通过线程来负责读取服务端数据
        Cilent3Thread t=new Cilent3Thread(client);
        t.start();
        //无限写入Scanner
        Scanner sc=new Scanner(System.in);
        System.out.print("请输入你的姓名:");
        String name=sc.nextLine();
        OutputStream os=client.getOutputStream();
        while (true){
            System.out.print("请输入你要聊天的内容(输入退出结束):");
            String msg=sc.nextLine();
            if ("退出".equals(msg)){
                os.write((name+"退出聊天室\n").getBytes());
                t.b=true; //结束读取服务器端信息的线程
                break;
            }else {
                os.write((name+"说:"+msg+"\n").getBytes());
            }
        }
        System.out.println("退出聊天室了");
    }
}

class Cilent3Thread extends Thread{
    Socket client;
    volatile boolean b=false;
    public Cilent3Thread(Socket client){
        this.client=client;
    }

    public void run() {
        try {
            BufferedReader br=new BufferedReader(new InputStreamReader(client.getInputStream()));
            while (true){
                String msg=br.readLine();
                System.out.println(msg);
                if (b) return;

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}